package org.academic.texteditor.gui.plugin.text;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.JMenu;
import javax.swing.KeyStroke;

import org.academic.texteditor.gui.component.PageContainer;
import org.academic.texteditor.gui.component.PersonalizedTextPane;
import org.academic.texteditor.gui.component.menu.MenuFactory;
import org.academic.texteditor.gui.feature.Page;
import org.academic.texteditor.gui.helper.ParagraphElement;
import org.academic.texteditor.gui.plugin.BasePlugin;

public class MoveTextUpPlugin extends BasePlugin {

	private static final long serialVersionUID = 1734577374799616764L;
	
	private PageContainer pageContainer;

	public MoveTextUpPlugin() {
		super("moveTextUp");
	}

	@Override
	public void initialize(PageContainer pageContainer) {
		this.pageContainer = pageContainer;
	}

	@Override
	public void activate() {
		JMenu menuEdit = MenuFactory.getEdit();
		MenuFactory.createMenuItem(menuEdit, 4, "moveTextUp", "menu.edit.moveTextUp", this).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP, ActionEvent.ALT_MASK));
	}

	@Override
	public void execute() {
		Page page = pageContainer.getActualPage();
		PersonalizedTextPane textPane = page.getText().getTextPane();
		
		ParagraphElement element = textPane.getParagraphElement();
		String text = element.getText() + "\n";

		int paragraphNumber = textPane.getParagraphNumber();
		if (paragraphNumber == 0) {
			return;
		}
		
		ParagraphElement previousElement = textPane.getParagraphElement(paragraphNumber - 1);
		int offset = previousElement.getStartOffset();
		
		textPane.removeParagraph();
		textPane.insert(offset, text);
		textPane.setCaretPosition(offset);
	}

	@Override
	public void deactivate() {
		JMenu menuEdit = MenuFactory.getEdit();
		MenuFactory.removeMenuItem(menuEdit, "moveTextUp");
	}

	@Override
	public void destroy() {

	}
}
